package cn.cmcc.online.smsapi.ui.util;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.cmcc.online.smsapi.ui.model.ActionData;
import cn.cmcc.online.smsapi.ui.model.FlightData;
import cn.cmcc.online.smsapi.ui.model.MetaData;
import cn.cmcc.online.smsapi.ui.model.MovieData;
import cn.cmcc.online.smsapi.ui.model.TableData;
import cn.cmcc.online.smsapi.ui.model.TrainData;

public class DataUtil {
    private static final String KEY_SELECT_INDEX = "usr_select_index";
    private static final String KEY_SELECT_GROUP = "usr_select_group";
    private static final String KEY_CARD_TYPE = "usr_select_type";
    private static final String KEY_WEB_DATA = "web_data";

    private static boolean isValidActionTime(String start, String end) {
        if (TextUtils.isEmpty(start) || TextUtils.isEmpty(end)) {
            return true;
        }

        long startTime = 0;
        long endTime = 0;
        try {
            startTime = Long.valueOf(start);
            endTime = Long.valueOf(end);
        } catch (Exception e) {
            e.printStackTrace();

        }

        if (startTime == 0 && endTime == 0) {
            return true;
        }

        long now = System.currentTimeMillis();
        if (startTime == 0) {
            return (now < endTime);
        } else if (endTime == 0) {
            return (now >= startTime);
        } else {
            return (now >= startTime && now < endTime);
        }
    }

    private static boolean isValidAction(ActionData action, String targetGroup) {
        Map<String, String> extra = action.getExtra();
        if (extra == null) {
            return true;
        }

        String group = action.getExtra().get(ActionData.KEY_GROUP);
        if (!TextUtils.isEmpty(group) && !targetGroup.startsWith(group)) {
            return false;
        }

        if (isValidActionTime(extra.get(ActionData.KEY_START_TIME), extra.get(ActionData.KEY_END_TIME))) {
            return true;
        }

        return false;
    }

    public static List<ActionData> getActionList(JSONObject obj) {
        String group = obj.optString(KEY_SELECT_GROUP);
        List<ActionData> sourceList = (List<ActionData>) obj.opt("action");
        if (sourceList == null) {
            return null;
        }

        List<ActionData> result = new ArrayList<>();
        for (ActionData actionData : sourceList) {
            if (TextUtils.isEmpty(group) || isValidAction(actionData, group)) {
                result.add(actionData);
                // max two button
                if (result.size() == 2) {
                    break;
                }
            }
        }

        return result;
    }

    public static String getSmsContent(JSONObject obj) {
        return obj.optString("sms_content");
    }

    public static boolean isTypeCard(JSONObject obj) {
        return obj.optBoolean(KEY_CARD_TYPE, true);
    }

    public static void switchCardType(JSONObject obj) {
        boolean card = !isTypeCard(obj);
        try {
            obj.put(KEY_CARD_TYPE, card);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static JSONArray getMainData(JSONObject obj) {
        JSONArray array = getData(obj).optJSONArray("main_info_data_arr");
        return array == null ? new JSONArray() : array;
    }

    public static List<TableData> getMainTableList(JSONObject obj) {
        JSONArray array = getMainData(obj);
        if (array == null) {
            return null;
        }

        List<TableData> list = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject tableObj = array.optJSONObject(i);
            list.add(new TableData(tableObj.optString("key"), tableObj.optString("value")));
        }

        return list;
    }

    private static JSONObject getData(JSONObject obj) {
        JSONObject data = obj.optJSONObject("data");
        return data == null ? new JSONObject() : data;
    }

    public static MovieData getMovieData(JSONObject obj) {
        MovieData movieData = null;
        try {
            JSONObject movieObj = getData(obj);
            if (movieObj != null) {
                movieData = new MovieData(movieObj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return movieData;
    }

    public static String getNote(JSONObject obj) {
        return getData(obj).optString("extra_info_tip");
    }

    public static long getReceiveTime(JSONObject obj) {
        return obj.optLong("msgTime");
    }

    public static MetaData getMetaData(JSONObject obj) {
        return new MetaData(obj);
    }

    public static List<TableData> getTableList(JSONObject obj) {
        JSONArray array = getData(obj).optJSONArray("extra_info_data_arr");
        if (array == null) {
            return null;
        }

        List<TableData> list = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject tableObj = array.optJSONObject(i);
            list.add(new TableData(tableObj.optString("key"), tableObj.optString("value")));
        }

        return list;
    }

    public static JSONObject getWebData(JSONObject obj) {
        return obj.optJSONObject(KEY_WEB_DATA);
    }

    private static void putWebData(JSONObject obj, JSONObject webData) {
        try {
            JSONObject webObj = getWebData(obj);
            if (webObj == null) {
                webObj = new JSONObject();
            }

            Iterator<String> iterator = webData.keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                webObj.put(key, webData.get(key));
            }

            obj.put(KEY_WEB_DATA, webObj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static FlightData getFlightData(JSONObject obj, int index) {
        try {
            obj.put(KEY_SELECT_INDEX, index);
            FlightData result = getFlightData(obj);
            if (result != null) {
                obj.put(KEY_SELECT_GROUP, result.getFlightNumber());
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static FlightData getFlightData(JSONObject obj) {
        FlightData flightData = null;
        try {
            JSONArray data = getMainData(obj);
            if (data != null) {
                int index = obj.optInt(KEY_SELECT_INDEX, 0);
                JSONObject flightObj = data.optJSONObject(index);
                if (flightObj != null) {
                    flightData = new FlightData(flightObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flightData;
    }

    public static void updateFlightJSONObject(JSONObject obj, FlightData data) {
        try {
            JSONArray flightArray = getMainData(obj);
            if (data != null) {
                int index = obj.optInt(KEY_SELECT_INDEX, 0);
                JSONObject trainObj = flightArray.optJSONObject(index);
                if (trainObj != null) {
                    data.updateJSONObject(trainObj);
                    flightArray.put(index, trainObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void updateJSONObject(JSONObject obj, TrainData data) {
        try {
            JSONArray trainArray = getMainData(obj);
            if (data != null) {
                int index = obj.optInt(KEY_SELECT_INDEX, 0);
                JSONObject trainObj = trainArray.optJSONObject(index);
                if (trainObj != null) {
                    data.updateJSONObject(trainObj);
                    trainArray.put(index, trainObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static TrainData getTrainData(JSONObject obj, int index) {
        try {
            obj.put(KEY_SELECT_INDEX, index);
            TrainData result = getTrainData(obj);
            if (result != null) {
                obj.put(KEY_SELECT_GROUP, result.getTrainNumber());
            }
            putWebData(obj, result.getWebData());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static TrainData getTrainData(JSONObject obj) {
        TrainData trainData = null;
        try {
            JSONArray data = getMainData(obj);
            if (data != null) {
                int index = obj.optInt(KEY_SELECT_INDEX, 0);
                JSONObject trainObj = data.optJSONObject(index);
                if (trainObj != null) {
                    trainData = new TrainData(trainObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trainData;
    }
}
